let shoppingPreferencesChart = null;

document.addEventListener('DOMContentLoaded', function() {
    loadShoppingPreferences();
});

function loadShoppingPreferences() {
    fetch('/api/shopping-preferences')
        .then(response => response.json())
        .then(data => {
            updateShoppingPreferencesChart(data);
        })
        .catch(error => {
            console.error('Error loading shopping preferences:', error);
        });
}

function updateShoppingPreferencesChart(data) {
    const ctx = document.getElementById('shoppingPreferencesChart').getContext('2d');
    
    // 如果图表已存在，销毁它
    if (shoppingPreferencesChart) {
        shoppingPreferencesChart.destroy();
    }
    
    // 生成随机颜色
    const colors = data.labels.map(() => {
        const r = Math.floor(Math.random() * 200);
        const g = Math.floor(Math.random() * 200);
        const b = Math.floor(Math.random() * 200);
        return `rgba(${r}, ${g}, ${b}, 0.7)`;
    });
    
    // 创建新图表
    shoppingPreferencesChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: data.labels.map((label, i) => `${label} (${data.percentages[i]}%)`),
            datasets: [{
                data: data.data,
                backgroundColor: colors,
                borderColor: colors.map(color => color.replace('0.7', '1')),
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        font: {
                            size: 12
                        },
                        padding: 20
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed || 0;
                            const percentage = data.percentages[context.dataIndex];
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}
